var express = require('express');
var articleModel = require('../model/articleModel');
require('../public/javascripts/DateFormat');

var router = express.Router();


// mongoose.connect("mongodb://localhost/myBlog");
// var db = mongoose.connection;

var mongoose = require('mongoose');
mongoose.connection.openUri('mongodb://localhost/myBlog');




router.get('/', function (req, res) {
    // res.send(req.query);

    var articleID = '';
    if (req.query.articleID) {
        articleID = req.query.articleID;
    }

    console.log('articleID: '+articleID);

    articleModel.findById(articleID, function (error, article) {
        if (!error) {
            var passValue = {
                article: article
            };

            res.render('update-article', passValue);
            // res.json(atricle);
        } else {
            res.send(error);
        }
    });
});



router.post('/update', function (req, res) {

    var articleID = '';
    if (req.query.articleID) {
        articleID = req.query.articleID;
    }

    if (!articleID) {
        return res.send('error');
    } else {

        var update_value = req.body;
        update_value.time = new Date().Format("yyyy-MM-dd hh:mm:ss");


        articleModel.findByIdAndUpdate(articleID, update_value, function (error, article) {
            if (!error) {
                // res.render('update-article', passValue);
                // res.json(atricle);

                console.log('article: '+JSON.stringify(article));
                // res.render('article');
                res.redirect("/article");
            } else {
                res.send(error);
            }
        });
    }

});


module.exports = router;
